﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.DwzFrame;
using Newtonsoft.Json;
using ZLCMS.Business.TranferParam;
using ZLCMS.Business.Util;
using NHibernate;
using ZLCMS.Business;
using NHibernate.Criterion;
using DotNet.Common.TransferParam;

namespace ZLCMS.Web.SystemManage.Basics.Param
{
    public partial class Add : System.Web.UI.Page
    {
        public class ItemExpData
        {
            public bool Enable;

            public string GroupCode;

            public string GroupName;

            public string Relation;

            public ItemExpData()
            {
                Enable = false;
                Relation = null;
            }
        }

        public ItemExpData[] _itemExpDataList;

        protected FrameHelper _framePage;

        protected SysParam _paramGroupDb;

        protected List<ParamGroupExp> _expGroupList;

        private const int MaxExp = 5;


        protected void Page_Load(object sender, EventArgs e)
        {
            _framePage = new FrameHelper(this);

            InitContent();

            InitVariable();

            InitControlData();

            if (!IsPostBack)
            {
            }
            else if (IsPostBack)
            {
                SaveDoc();
            }
        }

        /// <summary>
        /// 初始化全局变量
        /// </summary>
        private void InitVariable()
        {
            int i;
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    _paramGroupDb = session.CreateCriteria<SysParam>().Add(Expression.Eq("GroupCode", group_id.Value)).Add(Expression.Eq("ItemCode", item_id.Value)).UniqueResult<SysParam>();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                }
            }

            _expGroupList = JsonConvert.DeserializeObject<List<ParamGroupExp>>(_paramGroupDb.Param5 == null ? "" : _paramGroupDb.Param5);

            _itemExpDataList = new ItemExpData[MaxExp];

            for (i = 0; i < MaxExp; i++)
            {
                _itemExpDataList[i] = new ItemExpData();
            }

            if (_expGroupList != null)
            {
                i = 0;
                foreach (ParamGroupExp groupExp in _expGroupList)
                {
                    _itemExpDataList[i].Enable = true;
                    _itemExpDataList[i].GroupName = groupExp.Name;
                    _itemExpDataList[i].GroupCode = groupExp.Code;
                    _itemExpDataList[i].Relation = groupExp.Relation;
                    i++;
                }
            }
        }

        /// <summary>
        /// 初始化控件和控件的默认值
        /// </summary>
        private void InitControlData()
        {
            int i;

            if (!IsPostBack)
            {
                if (_expGroupList != null)
                {
                    i = 0;
                    foreach (ParamGroupExp groupExp in _expGroupList)
                    {
                        // 有关联参数，使用下拉框
                        if (groupExp.Relation != "" || groupExp.Relation != " " || groupExp.Relation != null)
                        {
                            // 初始化下拉框的内容
                            Bindddl(i, groupExp.Relation);
                        }
                        i++;
                    }
                }
            }
        }

        private void SetControlValue(int index, string value)
        {
            switch (index)
            {
                case 0: { ddl_list_0.SelectedValue = value; tb_list_0.Text = value; break; }
                case 1: { ddl_list_1.SelectedValue = value; tb_list_1.Text = value; break; }
                case 2: { ddl_list_2.SelectedValue = value; tb_list_2.Text = value; break; }
                case 3: { ddl_list_3.SelectedValue = value; tb_list_3.Text = value; break; }
                case 4: { ddl_list_4.SelectedValue = value; tb_list_4.Text = value; break; }
            }
        }


        private string GetControlValue(int index)
        {
            if (_itemExpDataList[index].Relation != "" || _itemExpDataList[index].Relation != " " || _itemExpDataList[index].Relation != null)
            {
                switch (index)
                {
                    case 0: return ddl_list_0.SelectedValue;
                }
            }
            else
            {
                switch (index)
                {
                    case 0: return tb_list_0.Text;
                }
            }
            return "";
        }

        private void Bindddl(int index, string group)
        {
            switch (index)
            {
                case 0: ParamKit.Bind(group, ddl_list_0, null, null, null, "-1", null);
                    break;
            }
        }

        private void InitContent()
        {
            if (!IsPostBack)
            {
                group_id.Value = Request["gid"];
                item_id.Value = Request["iid"];

                if (string.IsNullOrEmpty(group_id.Value) && string.IsNullOrEmpty(item_id.Value))
                {
                    _framePage.AlertAndCloseCurrent("操作出错：请先选择参数组。");
                }
            }
        }

        private void SaveDoc()
        {
            int i;
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                SysParam paramItemDb = new SysParam();

                paramItemDb.GroupCode = _paramGroupDb.ItemCode;
                paramItemDb.ItemCode = tb_code.Text;
                paramItemDb.ItemValue = tb_value.Text;

                List<ParamItemExp> itemExpList = new List<ParamItemExp>();

                for (i = 0; i < MaxExp; i++)
                {
                    if (!_itemExpDataList[i].Enable)
                    {
                        break; ;
                    }

                    itemExpList.Add(new ParamItemExp(_itemExpDataList[i].GroupCode, GetControlValue(i)));

                }
                paramItemDb.Param5 = JsonConvert.SerializeObject(itemExpList);

                try
                {
                    session.Save(paramItemDb);
                    session.Flush();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.InnerException.Message });
                }

                _framePage.Alert(new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功!",
                    callbackType = "closeCurrent"
                });
            }
        }
    }
}
